package ${domain}.module.wsys.mgr;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ${domain}.frame.auth.LocalData;
import ${domain}.frame.auth.Token;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.utils.IDgenerator;
import ${domain}.frame.utils.MapperUtil;
import ${domain}.frame.utils.Message;
import ${domain}.frame.utils.ValidationUtil;
import ${domain}.module.wsys.ent.Profiles;
import ${domain}.module.wsys.mpr.ProfilesMapper;
import ${domain}.module.wsys.req.ProfilesCreateRequest;
import ${domain}.module.wsys.req.ProfilesDeleteRequest;
import ${domain}.module.wsys.req.ProfilesFindRequest;
import ${domain}.module.wsys.req.ProfilesUpdateRequest;
import ${domain}.module.wsys.rsp.ProfilesCreateResponse;
import ${domain}.module.wsys.rsp.ProfilesDeleteResponse;
import ${domain}.module.wsys.rsp.ProfilesFindResponse;
import ${domain}.module.wsys.rsp.ProfilesUpdateResponse;

/**
 * PROFILES - 系统配置
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2020-07-06
 */
@Transactional
@Service
public class ProfilesManagerImpl implements ${domain}.module.wsys.mgr.ProfilesManager {

    @Autowired
    private ProfilesMapper profilesMapper;

    /**
     * 插入
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public ProfilesCreateResponse create(ProfilesCreateRequest request, Token token) {
        ProfilesCreateResponse response = new ProfilesCreateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        {// 配置项名唯一检查
            ProfilesFindRequest profilesFindRequest = new ProfilesFindRequest();
            profilesFindRequest.setKey(request.getKey());
            ProfilesFindResponse profilesFindResponse = this.find(profilesFindRequest, token);
            if (profilesFindResponse.hasError()) {
                response.addErrors(profilesFindResponse.getErrors());
                return response;
            } else if (profilesFindResponse.getTotalCount() > 0) {
                response.addError(ErrorType.UNIQUENESS_ERROR, "[key]配置项名已存在，请检查!");
                return response;
            }
        }

        long id = IDgenerator.nextId();
        ${domain}.module.wsys.ent.Profiles entity = MapperUtil.map(request, ${domain}.module.wsys.ent.Profiles.class);
        entity.setId(id);

        long result = profilesMapper.insert(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.CREATE_FAILURE);
            return response;
        }
        response.setId(id);

        return response;
    }

    /**
     * 逻辑删除
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public ProfilesDeleteResponse delete(ProfilesDeleteRequest request, Token token) {
        ProfilesDeleteResponse response = new ProfilesDeleteResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        long result = profilesMapper.delete(request.getId(), token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.DELETE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 更新
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public ProfilesUpdateResponse update(ProfilesUpdateRequest request, Token token) {
        ProfilesUpdateResponse response = new ProfilesUpdateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        ${domain}.module.wsys.ent.Profiles entity = profilesMapper.getById(request.getId(), token);
        if (entity == null) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.GET_FAILURE);
            return response;
        }

        MapperUtil.map(request, entity);
        long result = profilesMapper.update(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.UPDATE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 查询
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @Transactional(readOnly = true)
    public ProfilesFindResponse find(ProfilesFindRequest request, Token token) {
        ProfilesFindResponse response = new ProfilesFindResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getPageSize() != 0) {
            PageHelper.startPage(request.getPageNumber(), request.getPageSize());
        }
        if (StringUtil.isNotEmpty(request.getSortKey())) {
            PageHelper.orderBy(request.getSortKey() + " " + request.getSortType());
        }
        PageInfo<${domain}.module.wsys.ent.Profiles> pageInfo = new PageInfo<>(profilesMapper.find(request, token));

        response.setResult(pageInfo.getList());
        response.setTotalCount(pageInfo.getTotal());

        return response;
    }

    /**
     * 获得当前环境配置
     *
     * @param key          配置项名
     * @param defaultValue 默认值
     * @return
     */
    @Override
    public String getString(String key, String defaultValue) {
        ProfilesFindRequest profilesFindRequest = new ProfilesFindRequest();
        profilesFindRequest.setActive(LocalData.getActive());
        profilesFindRequest.setKey(key);
        ProfilesFindResponse profilesFindResponse = this.find(profilesFindRequest, LocalData.getSysToken());
        if (profilesFindResponse.hasError()) {
            return defaultValue;
        }

        if (profilesFindResponse.getResult().size() == 0) {
            // 主动保存未设置的键值
            Profiles entity = new Profiles();
            entity.setId(IDgenerator.nextId());
            entity.setActive(LocalData.getActive());
            entity.setKey(key);
            entity.setValue(defaultValue);
            profilesMapper.insert(entity, LocalData.getSysToken());
            return defaultValue;
        }

        return profilesFindResponse.getResult().get(0).getValue();
    }

    /**
     * 获得当前环境配置
     *
     * @param key          配置项名
     * @param defaultValue 默认值
     * @return
     */
    @Override
    public int getInt(String key, int defaultValue) {
        String string = this.getString(key, String.valueOf(defaultValue));
        if (!StringUtil.isEmpty(string)) {
            try {
                return Integer.parseInt(string);
            } catch (Exception ignored) {

            }
        }
        return defaultValue;
    }

    /**
     * 获得当前环境配置
     *
     * @param key          配置项名
     * @param defaultValue 默认值
     * @return
     */
    @Override
    public long getLong(String key, long defaultValue) {
        String string = this.getString(key, String.valueOf(defaultValue));
        if (!StringUtil.isEmpty(string)) {
            try {
                return Long.parseLong(string);
            } catch (Exception ignored) {

            }
        }
        return defaultValue;
    }

    /**
     * 获得当前环境配置
     *
     * @param key          配置项名
     * @param defaultValue 默认值
     * @return
     */
    @Override
    public boolean getBoolean(String key, boolean defaultValue) {
        String string = this.getString(key, String.valueOf(defaultValue));
        if (!StringUtil.isEmpty(string)) {
            try {
                return Boolean.parseBoolean(string);
            } catch (Exception ignored) {

            }
        }
        return defaultValue;
    }
}
